<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title></title>
		<link rel="stylesheet" type="text/css" href="../../css/api.css" />
		<link rel="stylesheet" type="text/css" href="../../css/style.css" />
		<link rel="stylesheet" type="text/css" href="../../css/btnplus.css" />
		<style type="text/css">
			html,body { height:100%; background-color: #F7F8FA; }
			.my_info{ padding-top: 10px;}
			.my_info ul{ margin-bottom: 20px; background-color: #fff;  overflow: hidden;}
			.my_info .top a{ padding: 12px;}
			.my_info .top h4{ display:block; font-size: 15px; color: #202532; font-weight: 500;}
			.my_info .top p{ display:block; font-size: 12px; color: #3262F1; font-weight: 400;}
			.my_info .top .m_cell_hd img{ width: 35px; height: 35px; border-radius: 4px;}
			.my_info .top .m_cell_ft img{ width: 6px; margin-left: 10px;}
			.my_info .list{ padding: 0 10px;}
			.my_info .list li{ height: 50px; position: relative; line-height: 50px; color: #202532;}
			.my_info .list li:not(:last-child)::after{ position: absolute; content: ""; left: 0; right: -10px; bottom: 0; border-bottom: 1px #d4d4d4 solid; transform: scaleY(0.5);}
			.my_info .list h4{ float: left; font-size: 15px; font-weight: 500;}
			.my_info .list p{ float: right; font-size: 14px; color:#333; font-weight: 400; }
			.color-333 { color: #333 !important; } 
			
			.footer{ position: fixed; left: 0; bottom: 0; right: 0; background-color: #000; z-index: 9;}
			.footer .con{ margin: 0 auto; width: 100%; box-sizing: border-box; padding: 0; position: relative;}
			.footer h4{ display:block; line-height: 50px; font-size: 15px; color: #fff; font-weight: normal;}
			.footer .left{ position: absolute; left: 0; top: 0; height: 50px; width: 50px; margin-left: 13px; overflow:hidden;}
			.footer .center {display:block; text-align: center; line-height: 32px;}
			.footer .right{ position: absolute; right: 13px; top: 0; height: 50px;}
			
			.display-none { display:none !important; }
		</style>
	</head>
	<body>
		<div class="my_info">
			<ul class="top">
				<a href="javascript:;" tapmode="lipress" onclick="setavatar();">
					<div class="m_cell_hd m_cell_primary"><h4 id="avatarstr">更换头像</h4><p id="avatarsh" class="display-none">头像审核中</p></div>
					<div class="m_cell_hd"><img src="../../image/defaultimg.png" id="avatar" /></div>
					<div class="m_cell_ft"><img src="../../image/img_13.png" alt="" /></div>
				</a>
			</ul>
			<ul class="top display-none" id="newavatardiv">
				<a href="javascript:;" tapmode="lipress" onclick="toast('头像审核中无法修改');">
					<div class="m_cell_hd m_cell_primary"><h4>新头像</h4><p>头像审核中</p></div>
					<div class="m_cell_hd"><img src="../../image/defaultimg.png" id="newavatar" /></div>
					<div class="m_cell_ft"><img src="../../image/img_13.png" alt="" /></div>
				</a>
			</ul>
			<ul class="list">
				<li>
					<h4>昵称</h4>
					<p id="realname">---</p>
				</li>
				<li>
					<h4>身份</h4>
					<p id="companyauth">-</p>
				</li>
			</ul>
		</div>
		<div class="footer display-none">
			<ul class="con">
				<div class="left" tapmode onclick="cancelPost();"><h4>取消</h4></div>
				<div class="center" tapmode onclick="resetImg();"><h4>还原</h4></div>
				<div class="right" tapmode onclick="saveAndPost();"><h4>确定</h4></div>
			</ul>
		</div>
	</body>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/app.js"></script>
	<script type="text/javascript" src="../../script/permission.js"></script>
	<script type="text/javascript">
		var sendtype; //当前编辑类型
		var content; //当前提交内容
		
		var FNImageClip;
		var canEdit = 0;
		apiready = function() {
			api.parseTapmode();
			FNImageClip = api.require('FNImageClip');
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (ret && ret.value)
				{
					var userinfo = JSON.parse(ret.value);
					updateuser(userinfo);
					getJsonFromAPI();
				}
			});
			api.addEventListener({
                name: 'navitembtn'
            }, function(ret, err) {
                if (ret.type == 'left') {
					api.closeWin({
					});
                }
            });
		}
		function getJsonFromAPI() {
			//从接口获取查询数据
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (ret.value) {
					var userinfo = JSON.parse(ret.value);
					api.ajax({
						url: ApiUrl + '/v1/userinfo',
						method: 'get',
						cache: false,
						timeout: 10,
						headers: {
							authorization: kAppKey+';'+userinfo.access_token+';'+userinfo.uid
						}
					}, function(ret, err) {
						
						if (ret) {
							if(ret.newavatar != '') {
								canEdit = 0;
								$api.text($api.byId('avatarstr'),'当前头像');
								$api.removeCls($api.byId('newavatardiv'),'display-none');
								$api.byId('newavatar').src = ret.newavatar;
								//$api.removeCls($api.byId('avatarsh'),'display-none');
							}
							else
							{
								canEdit = 1;
							}
							
							
						} else {
							if(err.statusCode==402)
							{
								Relogin();
							}
							else
							{
								toast('网络异常');
								console.log(JSON.stringify(err));
							}
						}
					});
				}
			});
		}
		function saveUserinfo() {
			api.showProgress({
				title: '请稍后...',
				text: '正在保存',
				modal: true
			});
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (ret && ret.value)
				{
					var userinfo = JSON.parse(ret.value);
					api.ajax({
						url: ApiUrl + '/v1/userinfo',
						method: 'post',
						cache: false,
						timeout: 10,
						headers: {
							authorization: kAppKey+';'+userinfo.access_token+';'+userinfo.uid
						},
						data: {
							values: {
								type: sendtype,
								content: content
							}
						}
					}, function(ret, err) {
						api.hideProgress();
						if (ret) {
							
							api.setPrefs({
								key: 'user_info',
								value: userinfo
							}, function(ret, err) {
								if(ret)
								{
									
								}
							});
							
							toast('保存成功');
						} else {
							console.log(JSON.stringify(err));
							toast(err.body.error);
						}
						
					});
				}
			});
		}
		function cancelPost() {
			$api.addCls($api.dom('.footer'),'display-none');
			FNImageClip.close(); //取消
		}
		function resetImg() {
			FNImageClip.reset(); //还原
		}
		function cacheImg(domId,url) {
			//缓存图片
			var resulturl = '';
			api.imageCache({
				url: url
			}, function(ret, err) {
				if(ret)
				{
					resulturl = ret.url;
					$api.attr($api.byId(domId),'src',ret.url);
				}
				else
				{
					resulturl = url;
					$api.attr($api.byId(domId),'src',url);
				}
			});
			
		}
		function updateuser(userjson) {
			//设置头像昵称等
			console.log(JSON.stringify(userjson));
			//var user = JSON.parse(userjson);
			var avatar = '../../image/defaultimg.png';
			if(userjson.access_token)
			{
				if(userjson.avatar!='')
				{
					avatar = userjson.avatar;
					
				}
				realname = userjson.realname;
			}
			else
			{
				avatar = '../../image/defaultimg.png';
				realname = '未登录';
			}
			$api.attr($api.byId('avatar'),'src',avatar);
			if(userjson.realname!='')
			{
				$api.html($api.byId('realname'), userjson.realname);
			}
			var companyauth = '车主';
			if(userjson.usertype == 2)
			{
				companyauth = '企业';
			}
			$api.text($api.byId('companyauth'),companyauth);
		}
		function setavatar() {
			//if(!$api.hasCls($api.byId('avatarsh'),'display-none')) {
			if(canEdit == 0) {
				toast('头像审核中无法修改');
				return false;
			}
			api.actionSheet({
				//title: '更换头像',
				cancelTitle: '取消',
				buttons: ['拍照', '从手机相册选择'],
				style: {
					layerColor:'rgba(0,0,0,0.3)',         //遮蔽层颜色，仅支持 rgba颜色，默认值：rgba（0, 0, 0, 0.4）
					itemNormalColor:'#fff',    //选项按钮正常状态背景颜色，支持#000、#000000、rgb、rgba，默认值：#F1F1F1
					itemPressColor:'#f5f5f5',     //选项按钮按下时背景颜色，支持#000、#000000、rgb、rgba，默认值：#E6E6E6
					fontNormalColor:'#333',    //选项按钮正常状态文字颜色，支持#000、#000000、rgb、rgba，默认值：#007AFF
					fontPressColor:'#000',     //选项按钮按下时文字颜色，支持#000、#000000、rgb、rgba，默认值：#0060F0
					titleFontColor:'#000'      //标题文字颜色，支持#000、#000000、rgb、rgba，默认值：#8F8F8F
				}
			}, function(ret, err) {
				if(ret.buttonIndex==1 || ret.buttonIndex==2)
				{
					getPicture(ret.buttonIndex);
				}
			});
		}
		function openAlbum() {
			getPicture(2);
		}
		function openCamera() {
			getPicture(1);
		}
		function getPicture(index){
			
			var perdesc = '相册/本地存储';
			var sourceType = 'library';
			var callbakstr = openAlbum;
            if(index==1){
				var pername = new Array('storage','camera');
				sourceType = 'camera';
				perdesc = '相册/拍照';
				callbakstr = openCamera;
				
				if (api.systemType == "android") {
					if(!confirmPerarr(pername,perdesc,callbakstr)){
						return;
					}
				}
			}
			else{
				var pername = 'photos';
				if (api.systemType == "android") {
					if(pername == 'photos')
					{
						pername = 'storage';
					}
					if(!confirmPer(pername,perdesc,callbakstr)){
						return;
					}
				}
			}
			api.getPicture({
				sourceType: sourceType,
				encodingType: 'png',
				mediaValue: 'pic',
				targetWidth: 600,
			}, function(ret, err) {
			// 获取图片数据并处理
				if (ret) {
					var imgSrc = ret.data;
					if (imgSrc != "") {
					
						selavatar(imgSrc);//选择图片后裁剪
					}
				}
			});
		}
		function selavatar(imgUrl) {
			$api.removeCls($api.dom('.footer'),'display-none');
			FNImageClip.open({
				rect: {
					x: 0,
					y: 0,
					w: api.winWidth,
					h: api.winHeight - document.querySelector('.footer').offsetHeight + api.safeArea.top + 45
				},
				srcPath: imgUrl,
				style: {
					mask: 'rgba(0,0,0,0.3)',
					clip: {
						w: 200,
						h: 200,
						x : (api.frameWidth - 200) / 2,
                        y : (api.frameHeight - 200) / 2,
						borderColor: '#0f0',
						borderWidth: 1,
						appearance: 'rectangle'
					}
				},
				mode: 'image'
			}, function(ret, err) {
				if (ret.status) {
					
					//alert(JSON.stringify(ret));
				} else {
					//alert(JSON.stringify(err));
				}
			});
		}
		function saveAndPost(){
			//裁剪成功开始处理，保存并上传
			
			api.showProgress({
				title: '请稍后...',
				text: '正在上传图片',
				modal: true
			});
			var imageCachePath = api.cacheDir;
			FNImageClip.save({
				destPath: imageCachePath+'/mylogo.png',
				copyToAlbum: false,
				quality: 1
			}, function(ret, err) {
				if (ret) {
					//alert(ret.destPath);
					var trans = api.require('trans');
					trans.decodeImgToBase64({
						imgPath: ret.destPath
					}, function(ret, err) {
						if (ret.status) {
							//转换成base64后上传
							uploadpic('data:image/jpeg;base64,'+ret.base64Str);
							//alert(ret.base64Str);
						} else {
							api.hideProgress();
							//alert(JSON.stringify(err));
						}
					});
				} else {
					//alert(JSON.stringify(err));
				}
			});
		}
		function uploadpic(base64str) {
			//上传头像
			api.getPrefs({
				key: 'user_info'
			}, function(ret, err) {
				if (ret && ret.value)
				{
					var userinfo = JSON.parse(ret.value);
					api.ajax({
						url: ApiUrl + '/v1/userinfo',
						method: 'post',
						cache: false,
						timeout: 10,
						headers: {
							authorization: kAppKey+';'+userinfo.access_token+';'+userinfo.uid
						},
						data: {
							values: {
								type: 'setavatar',
								base64str: base64str
							}
						}
					}, function(ret, err) {
						api.hideProgress();
						FNImageClip.close();
						$api.addCls($api.dom('.footer'),'display-none');
						if (ret) {
							//$api.removeCls($api.byId('avatarsh'),'display-none');
							var avatarurl = WebUrl+'/thumb/createthumb.php?path=/attachment/'+ret.picurl+'&type=avatar';
							canEdit = 0;
							$api.text($api.byId('avatarstr'),'当前头像');
							$api.removeCls($api.byId('newavatardiv'),'display-none');
							$api.byId('newavatar').src = avatarurl;
							
							toast('上传成功，请等待审核');
							//头像不是即时生效，注销下面代码
							
							//var cacheavatar = cacheImg('avatar',avatarurl); //显示缓存图片
							//userinfo.avatar = avatarurl+'&my';
							//api.setPrefs({
								//key: 'user_info',
								//value: userinfo
							//}, function(ret, err) {
							//});
							//var usersetting = 'updateuser('+ JSON.stringify(userinfo) +');';
							//api.execScript({
								//name: 'root',
								//frameName: 'my_frm',
								//script: usersetting
							//});
							//api.sendEvent({
								//刷新头像
								//name : 'refreshavatar'
							//});
							//toast('更换手机号成功');
						} else {
							console.log(JSON.stringify(err));
							toast(err.body.error);
						}
						
					});
				}
			});
		}
	</script>
</html>